package com.zxy.lm.controller;


import com.zxy.lm.VO.AnnouncementReleaseVO;
import com.zxy.lm.entity.Admin;
import com.zxy.lm.entity.Announcement;
import com.zxy.lm.service.AnnouncementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jiusi
 * @since 2021-06-23
 */
@Controller
@RequestMapping("/announcement")
public class AnnouncementController {

    @Autowired
    private AnnouncementService announcementService;

    @PostMapping("/release")
    public String release(HttpSession session, AnnouncementReleaseVO aVO, Model model) {
        Object o = session.getAttribute("admin");
        //只有管理员才能发布公告，下面是验证
        if (!(o instanceof Admin)) {
            return "redirect:/admin/login";
        }
        //创建新的公告
        Announcement announcement = new Announcement();
        announcement.setId(null)
                .setTitle(aVO.getTitle())
                .setContent(aVO.getContent())
                .setTime(LocalDateTime.now());
        //保存公告到数据库
        boolean save = announcementService.save(announcement);
        if (save) {
            return "redirect:/announcement";
        } else {
            model.addAttribute("rmsg", "添加失败");
            return "admin/releaseAnnouncement";
        }
    }
}

